<?php
namespace modules\auth;

class storage
{
    static function schemas(): array
    {
        return [
            'user' => [
                'id' => 'identity',
                'login' => 'string/256',
                'credential' => 'string/256',
                'role' => 'string',
                'seq' => '?string/' . security::RANDOM_ID_LENGTH,
            ],
        ];
    }

    static function add_user($q, string $login, string $password)
    {
        return self::new_user($q, $login, $password, 'user');
    }

    static function add_admin($q, string $login, string $password)
    {
        return self::new_user($q, $login, $password, 'admin');
    }

    static function user_info_from_login($q, string $login)
    {
        return $q->table('user')
            ->where(['login', $login])
            ->field('id', 'credential', 'role', 'seq')
            ->select(0);
    }

    static function user_info_from_seq($q, string $seq)
    {
        return $q->table('user')
            ->where(['seq', $seq])
            ->field('id')
            ->select(0);
    }

    static function revoke_token($q, $id)
    {
        return $q->table('user', $id)
            ->field('seq')
            ->update(security::random_id());
    }

    static function reset_password($q, $id, $password)
        // will revoke the token BTW.
    {
        return $q->table('user', $id)
            ->field('credential', 'seq')
            ->update(security::make_credential($password), security::random_id());
    }

    private static function new_user($q, $login, $password, $role)
    {
        return $q->table('user')
            ->field('login', 'credential', 'role', 'seq')
            ->insert($login, security::make_credential($password), $role, security::random_id());
    }
}

